﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Web.Framework.Config;
using Web.PuntoDeVenta.Code;
using Web.Framework;
using System.Web.Security;
using CrmContacto.Contracts.Contracts;
using System.Text;
using Web.Framework.Svc;
using CrmContacto.Contracts.Contracts.Search;
using Web.Framework.Translate;

namespace Web.PuntoDeVenta.Account
{
    public partial class Login : BasePage
    {
        protected void Page_PreLoad(object sender, EventArgs e)
        {         
            imgAr.Click += new ImageClickEventHandler(imgAr_Click);
            imgBr.Click += new ImageClickEventHandler(imgBr_Click);

            string cookieLenguaje = HttpHelper.GetCookieValue(LocalizationProvider.CookieLangKey, this.Request);
            if (!String.IsNullOrEmpty(cookieLenguaje))
            {
                if (cookieLenguaje != LocalizationProvider.Instance.GetCodigoLenguajeBySession())
                {
                    LocalizationHelper.ReInitialize(cookieLenguaje);
                    Server.Transfer(this.Page.Request.Path, false);
                }
            }           
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            masterPage.MakeMenuVisible(false);

            RegisterCompaniesIntoJS();

            List<string> cookieCompany = HttpHelper.GetCookieValues(HttpHelper.cookieCompany, this.Request);
            List<string> cookiePtoVta = HttpHelper.GetCookieValues(HttpHelper.cookiePtoVtaName, this.Request);           

            if (!this.IsPostBack)
            {
                bool showPtoVta = cookieCompany.Count > 1 && cookiePtoVta.Count > 1;
                if (showPtoVta)
                {
                    int companyId = Convert.ToInt32(cookieCompany[0]);
                    //PuntoDeVentaCurrentSession = null;
                    var ptoVta = GetPuntoDeVentaCurrent(companyId, false);
                    if (ptoVta != null)
                    {
                        DisplaySessionPuntoDeVenta(ptoVta);
                    }
                    else
                    {
                        showPtoVta = false;
                    }
                }

                if (!showPtoVta)
                {
                    this.lblPtoVtaInfo.Text = LocalizationProvider.Instance["Login.PtoVtaNoSeleccionado"];
                    hidPtoVta.Value = string.Empty;
                    hidSubPtoVta.Value = string.Empty;
                }

                //RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
                //LoginUser.Authenticate += new AuthenticateEventHandler(LoginUser_Authenticate);

                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

                BaseWebPage.ApplicationId = configuration.ApplicationId;
                BaseMasterPage.ApplicationId = configuration.ApplicationId;
                
                UIHelper.LoadCbo(WebServiceHelper.GetCompanies(BaseWebPage.ApplicationId), cboCompany, "Sin Especificar", value: "Name");

                // Selecciono la empresa en base a la cookie

                if (cookieCompany.Count > 0)
                {
                    this.cboCompany.SelectedValue = cookieCompany[0];                    
                }

                LoadComboPtoVtas();                
            }                
        }

        private void DisplaySessionPuntoDeVenta(CrmContacto.Contracts.Contracts.PuntoDeVenta ptoVta)
        {
            this.lblPtoVtaInfo.Text = ptoVta.DisplayName;
            hidPtoVta.Value = ptoVta.Id.ToString();
            var subPtoVta = ptoVta.SubPuntoDeVentaActual;
            if (subPtoVta != null)
            {
                hidSubPtoVta.Value = subPtoVta.Id.ToString();
                lblSubPtoVtaInfo.Text = LocalizationProvider.Instance["SubPuntoDeVentaText"] + " " + subPtoVta.Codigo;
            }
        }

        private void RegisterCompaniesIntoJS()
        {
            // Tengo que registrar el array en javascript
            StringBuilder builder = new StringBuilder();
            string separador = string.Empty;
            builder.Append("<script type='text/javascript' >");
            builder.Append("var companies = [];");
            foreach (CompanyConfiguration companyConfiguration in BasePage.GetCompanyConfigurationList(this.Page))
            {
                builder.AppendFormat("companies[{0}] = '{1}##{2}';", companyConfiguration.CompanyId, companyConfiguration.LogoImgFilePath, companyConfiguration.CssFilePath);
                //builder.AppendFormat("companies[{0}] = '{1}';", companyConfiguration.CompanyId, companyConfiguration.LogoImgFilePath);
            }

            builder.Append("</script>");
            Page.ClientScript.RegisterStartupScript(typeof(string), "companias", builder.ToString());
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");
                bool isAutenticated = false;

                // Agrego la cookie para el combo de punto de ventas     
                HttpHelper.SetCookieValues(HttpHelper.cookieCompany, this.Response, cboCompany.SelectedValue, cboCompany.SelectedItem.Text);

                int companyId = Convert.ToInt32(cboCompany.SelectedValue);
                var puntosDeVentaList = GetPuntosDeVentaDto(companyId);

                if (txtUserName.Text == configuration.SuperAdminName && txtPassword.Text == configuration.SuperAdminPassword)
                {
                    isAutenticated = true;
                    BaseMasterPage.IsAdmin = true;
                }
                else if (WebServiceHelper.Authenticate(BaseWebPage.ApplicationId, Convert.ToInt32(cboCompany.SelectedValue), txtUserName.Text, txtPassword.Text))
                {
                    isAutenticated = true;
                    BaseMasterPage.IsAdmin = false;
                }
                else
                {
                    // informar el error
                    this.masterPage.ShowMessage(LocalizationProvider.Instance["Login.UserPassError"], WebMessageType.Notification);
                }

                var ptoVta = puntosDeVentaList.Where(p => p.Id.ToString() == this.Request.Form[cboPtoVta.UniqueID]).Single();

                // SubId de punto de venta
                string subPtoVtaIdStr = this.Request.Form[cboSubPtoVta.UniqueID];
                hidSubPtoVta.Value = subPtoVtaIdStr;
                if (!String.IsNullOrEmpty(subPtoVtaIdStr))
                {
                    ptoVta.SubPuntoDeVentaIdActual = Convert.ToInt32(subPtoVtaIdStr);
                }
                else
                {
                    ptoVta.SubPuntoDeVentaIdActual = null;
                }

                BaseMasterPage.CompanyId = companyId;
                BaseWebPage.CompanyId = BaseMasterPage.CompanyId;

                HttpHelper.SetCookieValues(HttpHelper.cookiePtoVtaName, this.Response, ptoVta.Id.ToString(), ptoVta.Nombre, subPtoVtaIdStr);
                PuntoDeVentaCurrentSession = ptoVta;

                if (isAutenticated)
                {
                    BaseMasterPage.UserName = txtUserName.Text;

                    Session["Marca"] = Marca.GetMarca(BaseMasterPage.CompanyId);

                    // seteo el nombre del usuario en el login
                    string displayName = txtUserName.Text;
                    var adUser = WebServiceHelper.GetUsers(BaseWebPage.ApplicationId, BaseMasterPage.CompanyId, txtUserName.Text).SingleOrDefault();
                    if (adUser != null)
                    {
                        if (!String.IsNullOrEmpty(adUser.GivenName))
                        {
                            displayName = adUser.GivenName;
                        }
                    }

                    BaseWebPage.DisplayUserName = displayName;

                    // tengo que guardar toda la informacion que guardo en session para regenerarla

                    string userDataString = string.Format("{0}|{1}|{2}|{3}", BaseMasterPage.CompanyId.ToString(), BaseMasterPage.IsAdmin.ToString(), ptoVta.Id.ToString(), subPtoVtaIdStr);
                    // Create the cookie that contains the forms authentication ticket
                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(txtUserName.Text, false);
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                    DateTime expiration = ticket.Expiration;
                    bool isPersistent = ticket.IsPersistent;
                    if(chkRememberMe.Checked)
                    {
                        expiration = DateTime.Now.AddMonths(3);
                        isPersistent = true;
                    }                    

                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, expiration, isPersistent, userDataString);
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                    
                    Response.Cookies.Add(authCookie);
                    if (chkRememberMe.Checked)
                    {
                        authCookie.Expires = expiration;
                    }

                    string redirectUrl = FormsAuthentication.GetRedirectUrl(txtUserName.Text, false);
                    if (String.IsNullOrEmpty(redirectUrl))
                    {
                        redirectUrl = "/App/Customer.aspx";
                    }

                    Response.Redirect(redirectUrl);
                    
                    //FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);                    
                }
                else
                {
                    var tmpPtoVta = GetPuntoDeVentaCurrent(companyId, false);
                    if (tmpPtoVta != null)
                    {
                        this.hidPtoVta.Value = tmpPtoVta.Id.ToString();
                        if (tmpPtoVta.SubPuntoDeVentaIdActual.HasValue)
                        {
                            this.hidSubPtoVta.Value = tmpPtoVta.SubPuntoDeVentaIdActual.Value.ToString();
                        }
                        else
                        {
                            this.hidSubPtoVta.Value = string.Empty;
                        }

                        LoadComboPtoVtas();
                        DisplaySessionPuntoDeVenta(ptoVta);
                    }                                        
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }            
        }

        private void LoadComboPtoVtas()
        {            
            if (cboCompany.SelectedIndex >= 0)
            {
                int empresaId = Convert.ToInt32(cboCompany.SelectedValue);
                if (empresaId.ToString() != UIHelper.cboNullValue)
                {
                    var puntosDeVentaList = WebServiceHelper.GetPuntoDeVentaDto(new ServiceOptions(), new PuntoDeVentaSearch() { EmpresaId = empresaId, Activo = true, LoadSubPuntos = true });            

                    UIHelper.LoadCbo(puntosDeVentaList, cboPtoVta, string.Empty, "Id", "DisplayName");
                    
                    // Preselecciono el combo
                    string ptoVentaSelected = hidPtoVta.Value;
                    if (!String.IsNullOrEmpty(ptoVentaSelected))
                    {
                        var puntoDeVenta = puntosDeVentaList.Where(l => l.Id.ToString() == ptoVentaSelected).SingleOrDefault();
                        if (puntoDeVenta != null)
                        {                            
                            this.cboPtoVta.SelectedValue = ptoVentaSelected; // ver de poner un try por si falla al no estar el valor

                            UIHelper.LoadCbo(puntoDeVenta.SubPuntosDeVenta, cboSubPtoVta, string.Empty, "Id", "Codigo");
                            // Subpunto de venta
                            string subPtoVtaSelected = hidSubPtoVta.Value;
                            if (!String.IsNullOrEmpty(subPtoVtaSelected))
                            {
                                var subPuntoDeVenta = puntoDeVenta.SubPuntosDeVenta.Where(s => s.Id.ToString() == subPtoVtaSelected).SingleOrDefault();
                                if (subPuntoDeVenta != null)
                                {
                                    cboSubPtoVta.SelectedValue = subPtoVtaSelected;
                                }
                            }
                        }
                    }
                }
            }
        }

        protected void imgAr_Click(object sender, ImageClickEventArgs e)
        {
            LocalizationHelper.ReInitialize("Ar");
            HttpHelper.SetCookieValue(LocalizationProvider.CookieLangKey, this.Response, "Ar");

            Response.Redirect(this.Page.Request.Path, false);
            //Server.Transfer(, false);            
        }

        protected void imgBr_Click(object sender, ImageClickEventArgs e)
        {
            LocalizationHelper.ReInitialize("Br");
            HttpHelper.SetCookieValue(LocalizationProvider.CookieLangKey, this.Response, "Br");
            Response.Redirect(this.Page.Request.Path, false);
            //Server.Transfer(this.Page.Request.Path, false);
        }
    }
}
